import os
import re
import sys
import time
import configparser
from threading import Thread

from tinyutils.time.time_utils import TimeUtils
from tinyutils.config.config_utils import ConfigUtils


class Controller(object):
    """
    控制器类

    """

    def __init__(self):
        # 从返回的字典中获取配置文件的数据
        self.package_name, self.throttle, self.run_time = self.read_config().values()

        self.config = self.package_name.replace(".", "_")

    def async2(func):
        def wrapper(*args, **kwargs):
            thr = Thread(target=func, args=args, kwargs=kwargs)
            thr.start()

        return wrapper

    # 读取配置文件
    def read_config(self):
        # 读取配置文件的内容
        config = ConfigUtils('./config/monkey.ini')

        return config.get_values_in_dict()

    def run(self):
        self.start_monkey()
        self.kill_monkey(self.run_time)

    def start_monkey(self):
        report_name = 'report/' + self.config + "_" +"monkey_" + TimeUtils.get_current_time(is_strip=True) + ".log"
        monkey_scripts = r'adb shell monkey -p ' + self.package_name + \
                         r' --pct-syskeys 0 -s 1001 --throttle ' + self.throttle + \
                         r' --ignore-crashes --ignore-timeouts' \
                         r' --monitor-native-crashes -v -v -v 800000 >' + report_name
        os.popen(monkey_scripts)

    @async2
    def kill_monkey(self, run_time=0):
        """
        杀掉monkey进程

        :param run_time: 等待时间
        :return:
        """
        time.sleep(int(run_time))
        content = os.popen("adb shell ps | findstr monkey")
        pid = 0
        for line in content.readlines():
            pid_pattern = re.compile(r'\d+\b')
            pid = pid_pattern.findall(line)[0]
        os.system("adb shell kill " + str(pid))


if __name__ == '__main__':
    Controller().run()
